package model.semantics;

import java.util.ArrayList;
import java.util.List;

import model.State;
import model.parser.ParserException;

public class PopNode<T> extends Node<T> {
    private VariableNode<T> myVariable;

    public PopNode(Node<T> variable) {
        if (!(variable instanceof VariableNode)) {
            throw ParserException.BAD_ARGUMENTS;
        }
        myVariable = (VariableNode<T>) variable;
    }

    @Override
    public T evaluate(State<T> state) {
        // "Pop" an element by copying the array, removing one element, and
        // setting the
        // assignment.
        Node<T> valList = state.getAssignment(myVariable.getLabel());
        if (!(valList instanceof AggregatorNode)) {
            throw ParserException.BAD_ARGUMENTS;
        }

        List<Node<T>> oldList = ((AggregatorNode<T>) valList).getList();
        List<Node<T>> newList = new ArrayList<Node<T>>(oldList);
        // Remove element.
        Node<T> removedNode = newList.remove(0);

        AggregatorNode<T> newListNode = new AggregatorNode<T>(newList);
        state.setAssignment(myVariable.getLabel(), newListNode);

        return removedNode.evaluate(state);
    }

}
